<?php

namespace app\factory\logistics;

use think\facade\Cache;
use think\facade\Config;

class Logistics
{
    //快递鸟-物流请求

    private static $Id = "";//id
    private static $appkey = "";//key
    private static $url = "";//访问地址

    private $redis;
    private $redis_key;

    //构造
    public function __construct()
    {
        self::$Id = Config::get('system.kdn.id');//id
        self::$appkey = Config::get('system.kdn.appkey');//key
        self::$url = Config::get('system.kdn.url');//访问地址
        $this->redis = Cache::store('redis')->handler();
        $this->redis_key = 'panggua:traces_';
    }


    /**
     * Json方式 查询订单物流轨迹
     * @param string $OrderCode 商城订单编号
     * @param string $ShipperCode 快递编码
     * @param string $LogisticCode 运单号
     * @param string $CustomerName
     * @return string
     */
    public function getOrderTracesByJson($OrderCode = '', $ShipperCode = "", $LogisticCode = "", $CustomerName = '')
    {
        $redis_key = trim($ShipperCode . trim($LogisticCode));
        $data = $this->_getCache($redis_key);
        if ($data !== false) {
            return $data;
        }
        $LogisticCode = strtoupper($LogisticCode);
        $CustomerName = substr($CustomerName, -4);
        $requestData = "{'OrderCode':'" . $OrderCode . "','ShipperCode':'" . $ShipperCode . "','LogisticCode':'" . $LogisticCode . "','CustomerName':'".$CustomerName."'}";
        $appkey = self::$appkey;
        $url = self::$url;
        $datas = array(
            'EBusinessID' => self::$Id,//id
            'RequestType' => '8001',
            'RequestData' => urlencode($requestData),
            'DataType' => '2',
        );
        $datas['DataSign'] = urlencode(base64_encode(md5($requestData . $appkey)));
        //请求
        $temps = array();
        foreach ($datas as $key => $value) {
            $temps[] = sprintf('%s=%s', $key, $value);
        }
        $post_data = implode('&', $temps);
        $url_info = parse_url($url);
        if (empty($url_info['port'])) {
            $url_info['port'] = 80;
        }
        $httpheader = "POST " . $url_info['path'] . " HTTP/1.0\r\n";
        $httpheader .= "Host:" . $url_info['host'] . "\r\n";
        $httpheader .= "Content-Type:application/x-www-form-urlencoded\r\n";
        $httpheader .= "Content-Length:" . strlen($post_data) . "\r\n";
        $httpheader .= "Connection:close\r\n\r\n";
        $httpheader .= $post_data;
        $fd = fsockopen($url_info['host'], $url_info['port']);
        fwrite($fd, $httpheader);
        $gets = "";
        $headerFlag = true;
        while (!feof($fd)) {
            if (($header = @fgets($fd)) && ($header == "\r\n" || $header == "\n")) {
                break;
            }
        }
        while (!feof($fd)) {
            $gets .= fread($fd, 128);
        }
        fclose($fd);
        $data_temp = json_decode($gets, true);
        if (!empty($data_temp['Traces'])) {
            $this->_setCache($redis_key, $gets);
        }
        return $gets;
    }


    private function _getCache($key)
    {
        $redis_key = $this->redis_key . $key;
        $data = $this->redis->get($redis_key);
        if (empty($data)) {
            return false;
        }
        return unserialize($data);
    }

    private function _setCache($key, $data)
    {
        $redis_key = $this->redis_key . $key;
        $this->redis->set($redis_key, serialize($data), 3600 * 1);
    }
}